﻿using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System;
using XamlaApp.Model;
using XamlaApp.Interfaces;

namespace XamlaApp.Views.UIViews
{
    /// <summary>
    /// Dynamically generates a menu bar of Buttons for any IXamlaElements that exist in the application Unity container.
    /// </summary>
    public partial class ElementMenuBar : UserControl
    {
        private XamlaModel Model { get; set; }

        public ElementMenuBar()
        {
            InitializeComponent();

            Model = Container.AppContainer.Resolve<XamlaModel>();

            //ItemsControl cannot directly bind to a list of UIElement, so we convert it to a CLR object list
            //I'm ok with this approach because it only happens one time...
            List<ItemBinder> b = new List<ItemBinder>();
            var elements = Container.AppContainer.ResolveAll<IXamlaElement>();
            foreach (var t in elements)
            {
                b.Add(new ItemBinder
                {
                    Content = t.MenuButton, //displays inside the menu button
                    Element = t.GetType() //holds reference to the element Type for the click handler
                });
            }

            //now bind it
            DataContext = b;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            //create an instance of the element
            Model.AddElement((Type)((Button)sender).Tag);
        }
    }

    public class ItemBinder
    {
        public UserControl Content { get; set; }
        public Type Element { get; set; }
    }
}
